<?php
namespace app\admin\controller;
use think\Request;
use app\common\model\ConfigModel;
use app\common\controller\Backend;


class Config extends Backend
{

	public function index(Request $request = null){
  	$ConfigModel = new ConfigModel();
  	$list = $ConfigModel->getConfigList($request->get());

    foreach ($list['data'] as &$config) {
      $config = $this->transform($config);
    }

  	return view("index",[
  		'list' => $list,
  	]);
	}

	//创建页面
	public function create(Request $request = null){
    if(Request::instance()->isPost()){
      $post = $request->post();
      $ConfigModel = new ConfigModel();
      $result = $ConfigModel->allowField(true)->validate(true)->save($this->transform($post,'do'));
      if(false === $result){
        // 验证失败 输出错误信息
        $this->error($ConfigModel->getError());
      }else{

        $this->success("成功！");
      }
      
    }else{
      return view("create",[]);
    }
	}

   //更新页面
  public function update(Request $request = null){
    if($request->isPost()){
      $post = $request->post();
      $ConfigModel = new ConfigModel();
      $result = $ConfigModel->allowField(true)->validate(true)->save($this->transform($post,'do'), $post['id']);

      if(false === $result){
        // 验证失败 输出错误信息
        $this->error($ConfigModel->getError());
      }else{

        $this->success("成功！");
      }
    }else{
      $id = $request->param('id/d',0);
      $ConfigModel = new ConfigModel();
      $ConfigModel = $ConfigModel->getConfigById($id);
      $model = $this->transform($ConfigModel, 'update');
      
      return view($model['view'],$model['modelData']);
    }
  }

  /*删除*/
  public function deleteall(){
    $ConfigModel = new ConfigModel();
    if($ConfigModel->deleteall($_POST['id']) > 0){
      return json(['status'=>200,'msg'=>'成功']);
    }else{
      return json(['status'=>400,'msg'=>'失败']);
    }
  }

  //转化
  private function transform($config, $action="index"){
    if($action == 'do'){
      if($config['config_key'] == 'start_time'){
        $config['text'] = strtotime($config['text']);
        return $config;
      }
      return $config;
    }

    $config = [
      'id' => $config['id'],
      'config_key' => $config['config_key'],
      'config_value' => $config['config_value'],
      'config_type' => $config['config_type'],
      'remark' => $config['remark'],
    ];
    $config = array_merge($config, ['view'=>'update','modelData'=>['ConfigModel'=>$config]]);

    if($config['config_key'] == 'start_time'){
      $config['config_value'] = date('Y-m-d H:i:s',$config['config_value']);
      $config['view'] = 'time';
    }
    return $config;
  }
}